Examples of while loop to understand working concept of while loops in Python
Simple Counter
Simple counter using while loop in python
i = 0
while i < 10:
print(i)
i += 1
Output
0
1
2
3
4
5
6
7
8
9
Sum of Numbers
Sum of numbers inside a range using while loop in python
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
Output
The sum is 55
Factorial of a Number
Factorial of a number using while in python
num = 5
factorial = 1
while num > 1:
factorial *= num
num -= 1
print("Factorial is ", factorial)
Output
Factorial is 120
Fibonacci Series
Fibonacci series example using while loop in python
n = 10
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
Output
0 1 1 2 3 5 8
Guessing Game
Number guessing game in python using while loop
import random
number = random.randint(1, 10)
guess = 0
while number != guess:
guess = int(input('Guess a number between 1 and 10: '))
print('You guessed right!')
Output
Guess a number between 1 and 10:
6
Guess a number between 1 and 10:
6
Guess a number between 1 and 10:
1
Guess a number between 1 and 10:
2
Guess a number between 1 and 10:
3
Guess a number between 1 and 10:
3
Guess a number between 1 and 10:
4
You guessed right!
code executed successfully with code 0
Reverse a Number
Reversing number using while loop in python
num = 12345
reverse_num = 0
while num > 0:
digit = num % 10
reverse_num = reverse_num * 10 + digit
num = num // 10
print("Reversed Number is: ", reverse_num)
Output
Reversed Number is: 54321
Multiplication Table
Multiplication table using while loop in python
num = 5
i = 1
while i <= 10:
print(num, 'x', i, '=', num*i)
i += 1
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Countdown Timer
countdown using while loop in python
import time
countdown = 5
while countdown > 0:
print(countdown)
time.sleep(1)
countdown -= 1
print("Blast off!")
Output
5
4
3
2
1
Blast off!
Palindrome Check
Palindrome example in python using while loop
word = "madam"
reversed_word = ""
while len(word) > 0:
reversed_word += word[-1]
word = word[:-1]
print("Reversed word is: ", reversed_word)
Output
Reversed word is: madam
Prime Number Check
prime number example using while loop
num = 17
i = 2
is_prime = True
while i * i <= num:
if num % i:
i += 1
else:
is_prime = False
break
if is_prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
Output
17 is a prime number.
These examples should give you a good understanding of how to use while loops in Python